import axios from "axios";
// import { useUserState } from "@/store";
import eventEmitter from "./eventEmitter";
import config from "@/configs/globalConfig";
const AUTHORIZATION = "Authorization"; // 请求头
const TOKEN_PREFIX = "Bearer"; // token前缀
const TOKEN_KEY = "__TOKEN__"; // 缓存key
// const userState = useUserState();

const pendingPool = new Map(); // 存储取消请求的函数

/**
 * 添加取消请求的函数
 * @param {Object} config 配置对象
 */
export function addPendingRequest(config) {
  const requestKey = getRequestKey(config);
  const controller = new AbortController();
  config.signal = controller.signal;
  if (pendingPool.has(requestKey)) {
    pendingPool.get(requestKey).abort();
    pendingPool.delete(requestKey);
  }
  pendingPool.set(requestKey, controller);
  return controller;
}

/**
 * 移除请求
 * @param {Object} config 请求配置对象
 */
export function removePendingRequest(config) {
  const requestKey = getRequestKey(config);
  if (pendingPool.has(requestKey)) {
    pendingPool.delete(requestKey);
  }
}

/**
 * 取消所有请求
 */
export function cancelPendingRequests() {
  pendingPool.forEach((controller) => controller.abort());
  pendingPool.clear();
}

export function getPendingRequest(config) {
  const requestKey = getRequestKey(config);
  return pendingPool.get(requestKey);
}

function getRequestKey(config) {
  return `${config.method}_${config.url}`;
}

export const service = axios.create({
  baseURL: config.system.apiBaseURL,
  timeout: 10000,
  headers: { "Content-Type": "application/json" },
});

service.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem(TOKEN_KEY);
    if (token) {
      config.headers[AUTHORIZATION] = `${TOKEN_PREFIX} ${token}`;
    }
    const controller = addPendingRequest(config);

    eventEmitter.emit("request:before", config, controller);
    return config;
  },
  (error) => {
    console.log(error);
    eventEmitter.emit("request:error", error);
    return Promise.reject(error);
  }
);

service.interceptors.response.use(
  (response) => {
    removePendingRequest(response.config);
    if (response.status === 401) {
    }

    eventEmitter.emit("response:before", response);
    if (response.headers["Content-Type"] === "multipart/form-data") {
      return response;
    }
    return response.data;
  },
  (error) => {
    console.log(pendingPool);
    if (axios.isCancel(error)) {
      // 请求取消
      console.log("已取消请求");
      eventEmitter.emit("request:cancel", error);
      return;
    }
    eventEmitter.emit("response:error", error);
    pendingPool.clear(); // 报错清空
    return Promise.reject(error);
  }
);
